import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { GameState, DrawStroke, ChatMessage } from "../types/game";
import { websocketService } from "../services/websocket";
import { useUserStore } from "./user";
import { useGameConfigStore } from "./gameConfig";

export const useGameStore = defineStore("game", () => {
  // 状态
  const gameState = ref<GameState>({
    roomId: "",
    players: [],
    currentDrawer: null,
    currentWord: null,
    timeLeft: 0,
    gameStatus: "waiting",
    strokes: [],
    messages: [],
    round: 0,
    maxRounds: 5,
  });

  const isConnected = ref(false);
  const socket = ref<any>(null);
  const connectionError = ref("");
  const isReconnecting = ref(false);

  // 计算属性
  const currentPlayer = computed(() => {
    return gameState.value.players.find((p) => p.id === socket.value?.id);
  });

  const isCurrentDrawer = computed(() => {
    return gameState.value.currentDrawer === socket.value?.id;
  });

  const isDrawing = computed(() => {
    return gameState.value.gameStatus === "drawing" && isCurrentDrawer.value;
  });

  const gameProgress = computed(() => {
    if (!gameState.value.maxRounds) return 0;
    return ((gameState.value.round || 0) / gameState.value.maxRounds) * 100;
  });

  const canStartGame = computed(() => {
    return (
      gameState.value.players.length >= 2 &&
      gameState.value.gameStatus === "waiting"
    );
  });

  // 方法
  const updateGameState = (newState: Partial<GameState>) => {
    Object.assign(gameState.value, newState);
  };

  // 移除最后一笔
  const removeLastStroke = () => {
    if (isCurrentDrawer.value && gameState.value.strokes.length > 0) {
      gameState.value.strokes.pop();
      // 通知其他玩家
      socket.value?.emit("undoStroke");
    }
  };

  const addMessage = (message: ChatMessage) => {
    if (!gameState.value.messages) {
      gameState.value.messages = [];
    }
    gameState.value.messages.push(message);

    // 限制消息数量，避免内存泄漏
    if (gameState.value.messages.length > 100) {
      gameState.value.messages = gameState.value.messages.slice(-50);
    }
  };

  const connectToRoom = async (roomId: string, playerName: string) => {
    try {
      connectionError.value = "";
      isReconnecting.value = true;

      const socketInstance = await websocketService.connect();
      socket.value = socketInstance;
      isConnected.value = true;

      // 设置事件监听
      setupSocketListeners();

      // 加入房间
      websocketService.joinRoom(roomId, playerName);

      return true;
    } catch (error) {
      console.error("连接失败:", error);
      connectionError.value =
        error instanceof Error ? error.message : "连接失败";
      isConnected.value = false;
      return false;
    } finally {
      isReconnecting.value = false;
    }
  };

  const setupSocketListeners = () => {
    // 房间加入成功
    websocketService.onRoomJoined((data) => {
      if (data.success) {
        updateGameState(data.gameState);
        console.log("成功加入房间，玩家ID:", data.playerId);

        addMessage({
          id: Date.now().toString(),
          playerId: "system",
          playerName: "系统",
          content: "你已加入房间",
          type: "system",
          timestamp: Date.now(),
        });
      }
    });

    // 玩家加入/离开
    websocketService.onPlayerJoined((data) => {
      updateGameState({ players: data.players });

      addMessage({
        id: Date.now().toString(),
        playerId: "system",
        playerName: "系统",
        content: `${data.player.name} 加入了游戏`,
        type: "system",
        timestamp: Date.now(),
      });
    });

    websocketService.onPlayerLeft((data) => {
      updateGameState({ players: data.players });

      addMessage({
        id: Date.now().toString(),
        playerId: "system",
        playerName: "系统",
        content: "有玩家离开了游戏",
        type: "system",
        timestamp: Date.now(),
      });
    });

    // 游戏状态更新
    websocketService.onGameStateUpdated((data) => {
      updateGameState(data.gameState);
    });

    // 接收画笔数据
    websocketService.onStrokeReceived((data) => {
      addStroke(data.stroke);
    });

    // 画布清除
    websocketService.onCanvasCleared(() => {
      clearCanvas();
    });

    // 接收猜测
    websocketService.onGuessReceived((data) => {
      addMessage({
        id: Date.now().toString(),
        playerId: data.playerId,
        playerName: data.playerName,
        content: data.guess,
        type: data.isCorrect ? "correct" : "guess",
        timestamp: Date.now(),
      });

      if (data.isCorrect) {
        addMessage({
          id: (Date.now() + 1).toString(),
          playerId: "system",
          playerName: "系统",
          content: `${data.playerName} 猜对了！`,
          type: "system",
          timestamp: Date.now(),
        });
      }
    });

    // 游戏开始
    websocketService.onGameStarted((data) => {
      updateGameState(data.gameState);

      addMessage({
        id: Date.now().toString(),
        playerId: "system",
        playerName: "系统",
        content: "游戏开始！",
        type: "system",
        timestamp: Date.now(),
      });
    });

    // 回合结束
    websocketService.onRoundEnded((data) => {
      console.log("回合结束，正确答案:", data.correctWord);

      addMessage({
        id: Date.now().toString(),
        playerId: "system",
        playerName: "系统",
        content: `时间到！正确答案是：${data.correctWord}`,
        type: "system",
        timestamp: Date.now(),
      });
    });

    websocketService.onGameFinished?.((data) => {
      addMessage({
        id: Date.now().toString(),
        playerId: "system",
        playerName: "系统",
        content: "游戏结束！",
        type: "system",
        timestamp: Date.now(),
      });
    });

    // 错误处理
    websocketService.onError((data) => {
      console.error("WebSocket错误:", data.message);
      connectionError.value = data.message;

      addMessage({
        id: Date.now().toString(),
        playerId: "system",
        playerName: "系统",
        content: `错误：${data.message}`,
        type: "system",
        timestamp: Date.now(),
      });
    });
  };

  const disconnectFromRoom = () => {
    if (gameState.value.roomId) {
      websocketService.leaveRoom(gameState.value.roomId);
    }
    websocketService.disconnect();
    isConnected.value = false;
    socket.value = null;
    connectionError.value = "";
  };

  const addStroke = (stroke: DrawStroke, shouldSync = false) => {
    gameState.value.strokes.push(stroke);

    // 如果是本地绘制，同步到其他客户端
    if (shouldSync && gameState.value.roomId) {
      websocketService.sendStroke(gameState.value.roomId, stroke);
    }
  };

  const clearCanvas = (shouldSync = false) => {
    gameState.value.strokes = [];

    // 如果是本地清除，同步到其他客户端
    if (shouldSync && gameState.value.roomId) {
      websocketService.clearCanvas(gameState.value.roomId);
    }
  };

  const sendGuess = (guess: string) => {
    if (gameState.value.roomId && socket.value?.id) {
      websocketService.sendGuess(
        gameState.value.roomId,
        guess,
        socket.value.id
      );
    }
  };

  const startGame = () => {
    if (gameState.value.roomId) {
      // 获取游戏配置
      const userStore = useUserStore();
      const gameConfigStore = useGameConfigStore();

      websocketService.startGame(gameState.value.roomId, {
        roundTime: gameConfigStore.roundTime,
        wordBankId: gameConfigStore.selectedWordBankId,
      });
    }
  };

  const resetGameState = () => {
    gameState.value = {
      roomId: "",
      players: [],
      currentDrawer: null,
      currentWord: null,
      timeLeft: 0,
      gameStatus: "waiting",
      strokes: [],
      messages: [],
      round: 0,
      maxRounds: 5,
    };
  };

  return {
    gameState,
    isConnected,
    socket,
    currentPlayer,
    isCurrentDrawer,
    gameProgress,
    canStartGame,
    connectionError,
    isReconnecting,
    updateGameState,
    addStroke,
    clearCanvas,
    connectToRoom,
    disconnectFromRoom,
    sendGuess,
    startGame,
    addMessage,
    resetGameState,
  };
});
